package com.vn.ld.order.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.vn.ld.api.context.OrderSearchContext;
import com.vn.ld.api.exception.EntityNotFoundException;
import com.vn.ld.btc.dao.IOrderDao;
import com.vn.ld.btc.dao.entity.Order;
import com.vn.ld.common.Constants;
import com.vn.ld.common.domain.PageObjInfo;
import com.vn.ld.order.domain.queue.manager.CustomerOrderQueueManager;
import com.vn.ld.order.service.IOrderService;

@Service
public class OrderService implements IOrderService {
	private Logger log = Logger.getLogger(OrderService.class);
	
	@Autowired
	private IOrderDao<Order> orderDao;
	// TODO: Remove
/*	private static final String ORDER_BUY = "B";
	private static final String ORDER_SELL = "S";
	private static final String DELIMITER = "-";
*/	
	@Override
	public Boolean placeOrder(Order order) {
/*		// TODO: [START] Remove after move the order id generation to other place
		Date now = new Date();
		Integer custId = 1;
		StringBuilder orderId = new StringBuilder();
		
		if (order.getType().equals(1)) {
			orderId.append(ORDER_SELL);
		} else if (order.getType().equals(2)) {
			orderId.append(ORDER_BUY);
		}
		orderId.append(DELIMITER);
		orderId.append(custId);
		orderId.append(DELIMITER);
		orderId.append(DateUtils.dateToString(now, Constants.DATE_FORMAT_SECOND_TRUNCATE));
		// TODO: [END] Remove
		
		order.setOrderId(orderId.toString());
		this.orderDao.save(order);*/
		
		CustomerOrderQueueManager queueManager = CustomerOrderQueueManager.getInstance();
		queueManager.getCustOrderQueue().add(order);
		
		return true;
	}

	
	@Override
	public Boolean cancelOrder(String orderId) throws EntityNotFoundException {
		Order order = this.orderDao.findByID(Order.class, orderId);
		if (order != null) {
			order.setStatus(Constants.OrderStatus.ORDER_STATUS_CANCELLED);
			this.orderDao.save(order);
			return true;
		} else {
			log.error("Order not found with ID: " + orderId);
			throw new EntityNotFoundException("Order not found with ID: " + orderId);
		}
	}

	@Override
	public Boolean updateOrderStatus(String orderId, Integer status) throws EntityNotFoundException {
		Order order = this.orderDao.findByID(Order.class, orderId);
		if (order != null) {
			order.setStatus(status);
			this.orderDao.save(order);
			return true;
		} else {
			log.error("Order not found with ID: " + orderId);
			throw new EntityNotFoundException("Order not found with ID: " + orderId);
		}
	}

	@Override
	public Order getOrderByOrderId(String orderId) {
		return this.orderDao.findByID(Order.class, orderId);
	}

	@Override
	public List<Order> searchOrders(OrderSearchContext searchContext, PageObjInfo pagingInfo) {
		List<Order> result = new ArrayList<Order>();
		return result;
	}
}
